package com.item.mobile;

import static com.item.mobile.MobileUtil.checkParam;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.base.dialect.PaginationSupport;
import com.base.mobile.MobException;
import com.base.mobile.MobileInfo;
import com.base.mobile.server.annotation.Mobile;
import com.base.mobile.server.annotation.MobileMethod;
import com.base.util.DateUtil;
import com.base.util.StringUtil;
import com.item.dao.model.EssenceExample;
import com.item.dao.model.Post;
import com.item.dao.model.PostComment;
import com.item.dao.model.PostCommentExample;
import com.item.dao.model.PostExample;
import com.item.dao.model.PostPraise;
import com.item.dao.model.PostReport;
import com.item.dao.model.Unread;
import com.item.dao.model.UnreadExample;
import com.item.dao.model.User;
import com.item.service.EssenceService;
import com.item.service.PostCommentService;
import com.item.service.PostPraiseService;
import com.item.service.PostReportService;
import com.item.service.PostService;
import com.item.service.UnreadService;
import com.item.service.UserService;
import com.item.util.ConstantResources;
import com.item.util.MyDateUtils;
import com.item.util.MyStringUtils;
import com.mobile.api.proto.MAppPost.MPost;
import com.mobile.api.proto.MAppPost.MPostComment;
import com.mobile.api.proto.MAppPost.MPostComments;
import com.mobile.api.proto.MAppPost.MPosts;
import com.mobile.api.proto.MSystem.MRet;
import com.mobile.api.proto.MSystem.MUnreadCount;

@Component
@Mobile
public class MAppPost {
	@Autowired
	private PostService postService;
	@Autowired
	private PostCommentService commentService;
	@Autowired
	private UserService userService;
	@Autowired
	private PostPraiseService praiseService;
	@Autowired
	private PostReportService reportService;
	@Autowired
	private UnreadService unreadService;
	@Autowired
	private EssenceService essenceService;
	
	//type 1 hot, 2 time
	@MobileMethod(methodno = "MPosts", isLogin = false, isPage = true) 
	public MPosts.Builder index(MobileInfo mobileInfo, 
			Integer page, Integer limit, Integer type) throws Exception {
		MPosts.Builder ret = MPosts.newBuilder();
		
		PaginationSupport.setContext(page, limit, null);
		
		PostExample example = new PostExample();
		if(type == 1) {
			//hot post in 2 day2
			example.setOrderByClause("is_top DESC, " +
					"comment_count DESC, create_time DESC");
		} else {
			example.setOrderByClause("is_top DESC, create_time DESC");
		}
		
		List<Post> list = postService.selectByExample(example);
		for(Post p : list) {
//			p.setContent(MyStringUtils.contentTruncate(p.getContent()));
			assemblePost(ret, p);
		}
		
		return ret;
	}
	
	@MobileMethod(methodno = "MPostDetail", isLogin = false) 
	public MPost.Builder post(MobileInfo mobileInfo, 
			String postid) throws Exception {
		checkParam(postid, "postid");
		
		Post post = postService.selectByPrimaryKey(postid);
		MPost.Builder ret = assemblePost(null, post);
		
		if(StringUtils.isNotBlank(mobileInfo.getUserid())) {
			PostPraise key = new PostPraise();
			key.setPid(postid);
			key.setUserid(mobileInfo.getUserid());
			
			if(praiseService.selectByPrimaryKey(key) != null) {
				ret.setHasPraise(1);
			}
		} 
		
		if(ret == null) {
			throw new MobException(MEnumError.TREEHOLE_NOT_EXISTS);
		}
		
		return ret;
	}
	
	@MobileMethod(methodno = "MComments", isLogin = false, isPage = true)
	public MPostComments.Builder comments(MobileInfo mobileInfo, 
			String postid, Integer page, Integer limit) throws Exception {
		checkParam(postid, "postid");
		
		PaginationSupport.setContext(page, limit, null);
		
		MPostComments.Builder ret = MPostComments.newBuilder();
		
		PostCommentExample example = new PostCommentExample();
		example.createCriteria().andPidEqualTo(postid);
		example.setOrderByClause("create_time DESC");
		List<PostComment> list = commentService.selectByExample(example);
		
		String userid = StringUtil.emptyIfBlank(mobileInfo.getUserid());
				
		for(PostComment comment : list) {
			if(userid.equals(comment.getReplyId()) ||
					(userid.equals(comment.getPuserid()) && StringUtils.isBlank(comment.getReplyId()))) {
				comment.setIsNew(0); //alreay read
				commentService.updateByPrimaryKeySelective(comment);
			}
			
			assemebleComment(ret, comment,0);
		}
		
		return ret;
	}
	
	@MobileMethod(methodno = "MPostPublish", isLogin = true)
	public MRet.Builder publish(MobileInfo mobileInfo, 
			String content, String title) throws Exception {
		checkParam(content, "content");
		checkParam(title, "title");
		
		MRet.Builder ret = MRet.newBuilder();
		
		Post post = new Post();
		post.setUserid(mobileInfo.getUserid());
		post.setTitle(title);
		post.setContent(content);
		post.setCreateTime(new Date(System.currentTimeMillis()));
		
		User user = userService.selectByPrimaryKey(mobileInfo.getUserid());
		if(user != null) {
			post.setNickname(user.getNickname());
			post.setHeadimg(user.getHeadimg());
			post.setSex(user.getSex());
		}
		
		if(postService.insertSelective(post) > 0) {
			ret.setCode(1);
			ret.setMsg("发布成功");
		} else {
			ret.setCode(0);
			ret.setMsg("发布失败");
		}
		
		return ret;
	}
	
	@MobileMethod(methodno = "MCommentPublish", isLogin = true)
	public MRet.Builder commentPublish(MobileInfo mobileInfo, 
			String content, String postid, String replyid) throws Exception {
		checkParam(content, "content");

		MRet.Builder ret = MRet.newBuilder();
		
		PostComment comment = new PostComment();
		comment.setPid(postid);
		comment.setContent(content);
		comment.setCreateTime(new Date(System.currentTimeMillis()));
		comment.setUserid(mobileInfo.getUserid());
		User user = userService.selectByPrimaryKey(mobileInfo.getUserid());
		if(user != null) {
			comment.setNickname(user.getNickname());
			comment.setHeadimg(user.getHeadimg());
			comment.setSex(user.getSex());
		}
		if(StringUtils.isNotBlank(replyid)) {
			comment.setReplyId(replyid);
			User replyUser = userService.selectByPrimaryKey(replyid);
			if(replyUser != null) {
				comment.setReplyNickname(replyUser.getNickname());
			}
		} else {
			comment.setReplyId("");
		}
		Post post = postService.selectByPrimaryKey(postid);
//		System.out.println(replyid);
		if(post != null) {
			comment.setPtitle(post.getTitle());
			comment.setPuserid(post.getUserid());
			if(post.getUserid().equals(mobileInfo.getUserid())&&StringUtils.isBlank(replyid) || (StringUtils.isNotBlank(replyid) && mobileInfo.getUserid().equals(replyid))){
				comment.setIsNew(0);
//				System.out.println("不应该为1");
			}else{
				comment.setIsNew(1);
			}
//			if(!post.getUserid().equals(mobileInfo.getUserid()) || (StringUtils.isNotBlank(replyid) && !mobileInfo.getUserid().equals(replyid))) {
//				System.out.println("过来了");
//				comment.setIsNew(1);
//			} else {
//				comment.setIsNew(0);
//			}
		} else {
			throw new MobException(MEnumError.TREEHOLE_NOT_EXISTS);
		}
		
		int rows = commentService.insertSelective(comment);
		
		if(rows > 0) {
			int count = 0;
			while(count++ < 30) { //control times
				int commentCount = post.getCommentCount();

				PostExample example =
						new PostExample();
				example.createCriteria().andIdEqualTo(postid)
				.andCommentCountEqualTo(commentCount);
				post.setCommentCount(commentCount + 1);
				if(postService.updateByExample(post, example) > 0) {
					break;
				}
				post = postService.selectByPrimaryKey(postid);
				if(post == null) {
					throw new MobException(MEnumError.TREEHOLE_NOT_EXISTS);
				}
			}
			ret.setCode(1);
			ret.setMsg("发布成功");
		} else {
			ret.setCode(0);
			ret.setMsg("发布失败");
		}
		
		return ret;
	}
	
	@MobileMethod(methodno = "MPostPraise", isLogin = true)
	public MRet.Builder praise(PostPraise praise) throws Exception {
		MRet.Builder ret = MRet.newBuilder();
		
		checkParam(praise.getPid(), "pid");
		
		if(praiseService.selectByPrimaryKey(praise) == null) {
			praise.setCreateTime(new Date(System.currentTimeMillis()));
			
			int rows = praiseService.insertSelective(praise);
			if(rows > 0) {
				Post post = postService.selectByPrimaryKey(praise.getPid());
				if(post != null) {
					post.setPraiseCount(post.getPraiseCount() + 1);
					int s = postService.updateByPrimaryKeySelective(post);
					System.out.println(s);
				}
				ret.setCode(1);
			}
		}
		
		return ret;
	}
	
	@MobileMethod(methodno = "MPostReport", isLogin = true)
	public MRet.Builder report(PostReport report) throws Exception {
		MRet.Builder ret = MRet.newBuilder();
		
		checkParam(report.getPid(), "pid");
		
		if(reportService.selectByPrimaryKey(report) == null) {
			report.setCreateTime(new Date(System.currentTimeMillis()));
			
			int rows = reportService.insertSelective(report);
			if(rows > 0) {
				ret.setCode(1);
			} 
		} else {
			ret.setMsg("您已经过举报该贴");
		}
		
		return ret;
	}
	
	
	@MobileMethod(methodno = "MCommentsToMe", isLogin = true, isPage = true)
	public MPostComments.Builder commentToMe(MobileInfo mobileInfo,
			Integer page, Integer limit) 
			throws Exception {
		MPostComments.Builder ret = MPostComments.newBuilder();
		
		PaginationSupport.setContext(page, limit, null);
		
		PostCommentExample example =
				new PostCommentExample();
		example.createCriteria()
		.andPuseridEqualTo(mobileInfo.getUserid())
		.andReplyIdEqualTo("");
		
		PostCommentExample.Criteria criteria =
				example.createCriteria()
				.andReplyIdEqualTo(mobileInfo.getUserid());
		
		example.or(criteria);
		example.setOrderByClause("is_new DESC, create_time DESC");
		List<PostComment> list = commentService.selectByExample(example);
		
		for(PostComment comment : list) {
//			comment.setContent(MyStringUtils.contentTruncate(comment.getContent()));
			assemebleComment(ret, comment,1);
		}
		return ret;
	}
	
	
	private MPostComment.Builder assemebleComment(MPostComments.Builder pret, PostComment comment,int type) {
		MPostComment.Builder ret = null;
		
		if(comment != null) {
			ret = MPostComment.newBuilder();
			ret.setPid(comment.getPid());
			String content = comment.getContent();
			//对conent做一个截取，只有未读消息时才截取
			if(type == 1 && content.startsWith("回复")){
				content = content.substring(content.indexOf(":")+1);
			}	
			ret.setContent(content);
			ret.setHeadimg(StringUtil.emptyIfBlank(comment.getHeadimg()));
			ret.setId(StringUtil.emptyIfBlank(comment.getId()));
			ret.setNickname(StringUtil.emptyIfBlank(comment.getNickname()));
			ret.setReplyid(StringUtil.emptyIfBlank(comment.getReplyId()));
			ret.setReplyNickname(StringUtil.emptyIfBlank(comment.getReplyNickname()));
			ret.setTime(DateUtil.getLnow(comment.getCreateTime()));
			ret.setUserid(comment.getUserid());
			ret.setIsNew(comment.getIsNew());
			ret.setTitle(comment.getPtitle());
			ret.setSex(comment.getSex());
			if(pret != null)
				pret.addComments(ret);
		}
		return ret;
	}
	
	
	
	private MPost.Builder assemblePost(MPosts.Builder pret, Post post) {
		MPost.Builder ret = null;
		
		if(post != null) {
			ret = MPost.newBuilder();
			ret.setCommentCount(post.getCommentCount() 
					== null ? 0 : post.getCommentCount());
			ret.setContent( post.getContent());
			ret.setHeadimg(StringUtil.emptyIfBlank(post.getHeadimg()));
			ret.setId(StringUtil.emptyIfBlank(post.getId()));
			ret.setLastTime(post.getLastTime() == null ?
					 "" : DateUtil.getLnow(post.getLastTime()));
			ret.setTime(DateUtil.getLnow(post.getCreateTime()));
			ret.setNickname(StringUtil.emptyIfBlank(post.getNickname()));
			ret.setTitle(StringUtil.emptyIfBlank(post.getTitle()));
			ret.setSex(post.getSex());
			ret.setUserid(StringUtil.emptyIfBlank(post.getUserid()));
			ret.setPraiseCount(post.getPraiseCount() == null ? 0 : post.getPraiseCount());
			ret.setSharedUrl(String.format("%s?id=%s&t=%d", ConstantResources.POSTSHAREURL,post.getId(),System.currentTimeMillis()));
			if(pret != null)
				pret.addList(ret);
		}
		return ret;
	}

}
